var QS_Sector=function($container,cfg){
	this.$container = $container;
	this.cfg={
		w:620,
		h:500,
		minWidth:600
	}
	$.extend(this.cfg,cfg);
	this.cfg.height-=26;
	this.view = null;
	this.sdEl = null;
	this.sectorDetailObj = null;
	this.id=null;
	this.$settingPanel=null;
	this.originTitle = QS_Lang.sectordetail["sect_origintitle"];
	GOLBAL_DATA.InstitutionSecuritityTypePermission = {QUEST:{ST:true,FE:true,XI:true}};
	
	this.$container.append('<div class="qs-sectorList-wrap"></div>'+
							'<div class="qs-sectorDetail-wrap"></div>');
	this.slEl=this.$container.find(".qs-sectorList-wrap");
	this.sdEl=this.$container.find(".qs-sectorDetail-wrap");
    this.winId = this.$container.attr("id");
//	this.init("ms","USA");
};
QS_Sector.prototype ={
	init:function(type,region){
		var self = this;
		
//		this.container.html("");
		this.slEl.html("");
//		this.sdEl.html("");
		this.sectorList=new QS_SectorList(type,this.slEl,"",region,this.cfg,{onClick:function(sectorName,sectorType,region, name){
			self.sectorList.hide();
			self.sdEl.show();
			self.regionDDL.setDisable(true);
			self.__winObj.titleContainer.text(self.originTitle + ' : ' + name);
			if(self.sectorDetailObj==null){
				self.sectorDetailObj = new QS_SectorDetail(self.winId);
			}
			self.sectorDetailObj.init(self.sdEl,sectorName,sectorType,region,$.extend(self.cfg,{
				onBackClick:function(){
					self.sdEl.hide();
					self.sectorList.show();
					self.regionDDL.setDisable(false);
					self.__winObj.titleContainer.text(self.originTitle);
				}
//				afterInit:function(){
//					self.scrollPanel.reSize();
//				}
			}));

		}});
	},
	_getHTML:function(){
		return "<div class='qs-sectorList-wrap'></div><div class='qs-sectorDetail-wrap'></div>";
	},
    updateData:function(gKey,needupdatefiled){
		if(this.sectorDetailObj){
			this.sectorDetailObj.updateData(gKey,needupdatefiled);
		}
    },
	changeOutSize:function(w,h){
		var parent = this.$container.parent();
        w = w||parent.width();
        h = h||parent.height();
		
		if(w<this.cfg.minWidth){
			w=this.cfg.minWidth;
//			w+=12;
		}
//		w = Math.max(w,this.cfg.minWidth);
		
		if(this.sectorDetailObj){
			this.sectorDetailObj.changeOutSize(w,h);			
		}
		if(this.sectorList){
			this.sectorList.changeOutSize(w,h);			
		}
		
		this.cfg.width=w;
		this.cfg.height=h;
	},
	
	getSettingPanelDOM:function(){
		var self=this;
        $settingPanel=$('<div style="padding-top:10px;"><h5>Region</h5><div class="qs-sector-sp-ddl"></div></div>');
		var $ddlCtn=$settingPanel.find('.qs-sector-sp-ddl');

		this._createDDL($ddlCtn);
		return $settingPanel;
	},
	
	onOpenSettingPN:function(){
//		alert("open settingpn");
	},
	
	DDLMenuData:[
	{
        val:'usa',
        txt:QS_Lang.sectordetail["sect_ddlusa"]
    },
	{
        val:'can',
        txt:QS_Lang.sectordetail["sect_ddlcan"]
    }],
	
	_createDDL:function($container){
        var self=this;
        this.regionDDL=new Util.DropDownList($container,function(t, v){
			self.init("ms",v);
			
        },this.DDLMenuData,{
			actionAtInit:false,
            width:"100%"//142
        });
//        this.typeDDL.setTextValue(null,this.config.type);
    }
};

//sector detail
var QS_SectorDetail= function(containerId){
	this.el=null;
	this.qsTValidation =new tickerValidation(0, "", "qsTValidation");
    this.containerId=containerId;
};
QS_SectorDetail.prototype={
	init:function(container,sectorName,sectorType,region,cfg){
		var self = this;
		this.$container = $(container);

		if(this.el == null){
			this.el=$("<div class='qs-sectorDetail-chart-wrap'></div>"+
//						'<div class="qs-sectorDetail-fixchart" style="width:auto;height:31px"></div>'+
						'<div class="qs-sectorDetail-drag"></div>'+
						"<div class='qs-sectorDetail-list-wrap'></div>").appendTo(this.$container);
		}
		this.sdcEl=this.$container.find(".qs-sectorDetail-chart-wrap");
		this.sdlEl=this.$container.find(".qs-sectorDetail-list-wrap");
		this.dragEl=this.$container.find(".qs-sectorDetail-drag");
		this.sdcEl.html("");
//		this.sdlEl.html("");

		this.cfg={chartH:0.65,listH:0.35,dragH:3};
		$.extend(this.cfg,cfg);
		if(this.cfg.width<this.cfg.minWidth){
			this.cfg.width=this.cfg.minWidth;
//			this.cfg.width+=12;
		}
		
		this.nDefaultChecked=3;
		this.sdcEl.css({width:"auto", height:this.cfg.height*this.cfg.chartH});
		this.dragEl.css({width:"auto", height:this.cfg.dragH, background:"gray",cursor:"row-resize"});
		this.sdlEl.css({width:"auto", height:this.cfg.height*this.cfg.listH-this.cfg.dragH});
		
		//bind drag event
		var bDraged = false;
		var originPageY;
		var originChartH;
		var originListH;
		this.dragEl.unbind("mousedown").bind("mousedown",function(e){
			bDraged = true;
			originPageY=e.pageY;
			originChartH = self.currentChartH;
			originListH = self.currentListH;
			self.el.removeClass('qs-sector-cursor-default').addClass("qs-sector-cursor-rowresize");
		});
		this.el.unbind("mousemove").bind("mousemove",function(e){
			if(!bDraged)return;
//			setTimeout(function(){
//			var diffH=e.pageY - originPageY;
//			self._changeChartSize(self.cfg.width,originChartH+diffH);
//			self._changeListSize(self.cfg.width,originListH-diffH);
//			},0);
		});
		this.el.unbind("mouseup").bind("mouseup",function(e){
			if(!bDraged)return;
			bDraged = false;
			
			self.el.removeClass('qs-sector-cursor-rowresize').addClass("qs-sector-cursor-default");
			
			var diffH=e.pageY - originPageY;
			self._changeChartSize(self.cfg.width,originChartH+diffH);
			self._changeListSize(self.cfg.width,originListH-diffH);
		});
		
		this.el.unbind("selectstart").bind("selectstart",function(e){
			if(!bDraged)return;
			e.preventDefault();
			e.stopPropagation();
		});
		this.el.unbind("dragstart").bind("dragstart",function(e){
			if(!bDraged)return;
			e.preventDefault();
			e.stopPropagation();
		});
		
		if(sectorType == "ms"){
			QS_watchlistDataManager.subScribeSectorWatchList(sectorType,sectorName,null,region);
		}else{
			QS_watchlistDataManager.subScribeSectorWatchList(sectorType,sectorName,sectorName,region);
		} 
		QS_watchlistDataManager.getHoldings("sector_"+sectorName+"_"+region,function(holdings){
			self._onHoldingsCallback(holdings,sectorName,region);
		})
	},
	_onHoldingsCallback:function(holdings,sectorName,region){
		var self =this;
		//init ticker list
		this.initTickerList(holdings,sectorName,region);
	
		this.mt = "";
		this.ct=[];

		if(holdings.length==0){
			//init chart
			self.initWebChart(this.mt,this.ct);
			
			self.changeOutSize(self.cfg.width,self.cfg.height);
			if(typeof self.cfg.afterInit=="function"){
				self.cfg.afterInit();
			}
		
		}else{
		
			var tickers= [];
			for(var i=0;i<holdings.length;i++){
				tickers.push(holdings[i].SecId);

			}
			this.qsTValidation.showAlert = false;
			this.qsTValidation.checkTickers(tickers.join(","),function(list){  // filter the
			
				var lgg = list.length; stt=[];
				if(list&&list.length){
						
					for(var i=0;i<lgg;i++){
						var id =  gData[list[i]]["performanceId"];
						if(i==0)self.mt = id;  // main ticker for chart.
						if(i<self.nDefaultChecked)self.ct.push(id);  // compair tickers for chart.
//						stt.push(id);
					}

				}
				
				//init chart
				self.initWebChart(self.mt,self.ct);
				
				self.changeOutSize(self.cfg.width,self.cfg.height);
				if(typeof self.cfg.afterInit=="function"){
					self.cfg.afterInit();
				}
			
			},false);
		}
	},
	
	initTickerList:function(holdings,sectorName,region){
		//init ticker list
		var self=this;

		if(self.list==null){
			QS_WatchlistColumns["pid"]={
				"sortable": false,
				"dataType": "checkbox",
				"width": 20,
				"align": "left",
				"dataIndex": "pid",
				"header": QS_Lang.watchlist["checkbox"],
				renderer: function(txt){
					return '<input key="' + txt + '" type="checkbox">';
				}
			};
			var factor="7.0%";
			var profile = {
				currentId: "sector_"+sectorName+"_"+region,
				width: this.cfg.width,
				height: this.cfg.height*this.cfg.listH-this.cfg.dragH,
				settingPnCtn:null,
				autoWidth:true,
//				maxTicker:200,
				limitMessage:QS_Lang.text["watchlistlimitmsg"],
//				autoHeight:true,
//				subscribeInvisibleTickers:true, // subscribe all tickers.
				headerContextMenu:false,
				viewKey:[{dataIndex:'pid',header:"",width:"4%"},//ellipsis:true
						{dataIndex:'Symbol',width:factor,align:"left"},
						{dataIndex:'Name',width:"16%",align:"left"},
						{dataIndex:'LastPrice',width:factor},
						{dataIndex:'Chg',width:factor},
						{dataIndex:'Chg%',width:factor},
						{dataIndex:"OpenPrice",width:factor},
						{dataIndex:"HighPrice",width:factor},
						{dataIndex:"LowPrice",width:factor},
						{dataIndex:"Volume",width:"10%"},			
						{dataIndex:"st159",width:"14%"},
						{dataIndex:'remove',width:"4%"}]
			};
			
			var callback={
				onRowRemove: function(id, row){
				
				},
				onCellClick: function(e,cell,row){

					if(e.target.tagName!="INPUT" || e.target.type!="checkbox"){
						return;
					}

					var pid = row.data.SecId;
					if(e.target.checked){
						if(self.chartweb!=null){
							if(self.chartweb.chartComponent.mainTicker==""||self.chartweb.chartComponent.mainTicker==null){
								self.chartweb.chartComponent.acceptTicker(pid);
							}else{
								self.chartweb.chartComponent.addCompairTickers(pid);
							}
						}
					}else{
						if(self.chartweb!=null){
							if(pid==self.chartweb.chartComponent.mainTicker){
								self.chartweb.chartComponent.removeMainTicker(true);
							}else{
								self.chartweb.chartComponent.removeCompairTicker(pid);
							}
						}
					}
					if(self.chartweb.chartComponent.mainTicker==""){
						$(".qs-webchart-mask").show();
					}else{
						$(".qs-webchart-mask").hide();
					}
				},
				afterRebindData: function(DOMMap, rows){
/*					self.list.grid.el.find("input[key='"+self.mt+"']").attr("checked",true);//.attr("disabled",true);
					self.list.grid.el.find("input[key='"+self.ct[0]+"']").attr("checked",true);
					self.list.grid.el.find("input[key='"+self.ct[1]+"']").attr("checked",true);
*/
					var $input=self.list.grid.el.find("input");
					for(var i=0;i<self.nDefaultChecked;i++){
						$input.eq(i).attr("checked",true);
					}
				},
				afterAddTickers :function(){
				}
			};
			
			self.list=new QS_tickerList(self.sdlEl,profile,callback);
			self.list.setTickerValidation(new tickerValidation(0));
		}else{
			self.list.config.currentId = "sector_"+sectorName+"_"+region;
		}
		var stt = [];
		/*for(var i=holdings.length-1;i>=0;i--){
			if(!holdings[i].SecId || holdings[i].SecId=="") continue;
			stt.push(holdings[i].SecId);
		}*/
		//self.list.addTickers(stt);
		self.list.reBindData(holdings);
	},
    updateData:function(gKey,needupdatefiled){
        this.list.updateData(gKey,needupdatefiled);
    },
	
	initWebChart:function(mt,ct){
	
		this.createWebChart(mt,ct);
		
	},
	
	createWebChart:function(mt,ct){
//			var width=null;
//			var heigth=null;
			var self=this;
			var statusCfg={},mainTicker;
			var stateStr = null;
			if(stateStr!=null){
				 statusCfg = stateStr;
			}
			if(statusCfg.width==null){
				statusCfg.width = this.cfg.width;//630;			
			}
			if(statusCfg.height==null){
				statusCfg.height = this.cfg.height*this.cfg.chartH-31;
			}
			mainTicker = statusCfg.mTicker = mt;//"XNAS:MSFT"
			statusCfg.bTerminalUrlPath=true;
			var ty = 1;
			var ucfg = "compare,indicators,fundamental,drawing,display,foot,range|dateInputs-frequency";
			var showAuto = false;
			var cPush = 1;
			var cTickers = ct;
			var uiCfg = {showReset:false};
			
			this.chartweb =new chartWebPage(ty,statusCfg,ucfg,this.sdcEl,this.containerId+"_wchart","chartweb",showAuto,null,cPush,cTickers,uiCfg);
			this.chartweb.chartComponent.afterRemoveTickers=function(data){
				var key = data.symbol.gkey;
				var value = (typeof(gData)!="undefined"&&key&&gData[key])?gData[key]["performanceId"]:key;
				var rows=self.list.grid.rows;
				for(var i in rows){
					if(typeof rows[i].data.SecId =='undefined')continue;
					if(rows[i].data.SecId==value){
						rows[i].el.find('input').attr("checked",false);
						break;
					}
				}
//				var pid = row.data.SecId;
				
//				if(self.list){
//					self.list.grid.el.find("input[key='"+value+"']").attr("checked",false);
//				}
			}
			this.chartweb.chartComponent.hasConfirmBox = false;
			this.sdcEl.find(".qs-urlchart-range .reset").hide();
			this.createBackBtn(this.sdcEl);
			
	},
	
	createBackBtn:function($chartContainer){
		var self=this;
		var $btnContainer=$chartContainer.find(".qs-urlchart-zoom-con");
		var btn=$('<a href="javascript:void(0);" class="qs-sector-backbtn">'+QS_Lang.sectordetail["sect_backbtn"]+'</a>').appendTo($btnContainer);//qs-urlchart-range
		
		if(typeof this.cfg.onBackClick == "function"){
			btn.click(function(){
				self.list.reBindData([]);
				self.cfg.onBackClick()
			});
		}
	},
	
	changeOutSize:function(w,h){
		this._changeChartSize(w, h*this.cfg.chartH);
		this._changeListSize(w, h*this.cfg.listH-this.cfg.dragH);

		this.cfg.width=w;
		this.cfg.height=h;
	},
	_changeChartSize:function(w,h){
		this.sdcEl.css({width:"auto", height:h});
		this.chartweb&&this.chartweb.chartComponent.changeOutSize(w, h-31);
		this.currentChartH=h;
	},
	_changeListSize:function(w,h){
		this.list&&this.list.changeOutSize(w, h);
		this.currentListH=h;
	}
};

var QS_SectorList = function(type,container,linkBaseUrl,region,cfg,callback){
	this.cfg=cfg;
    this.type = type;
    this.$container = $(container);
    this.data = null;
    this.cols = 3;// 
    this.linkBaseUrl = linkBaseUrl;
	this.callback=$.extend(true,{onClick:null},callback);
    this.region = region||"USA";
	this.scrollPanel = new Util.ScrollPanel(this.$container);
	this.bChangeOutSized = false;
    this._init();
};
QS_SectorList.prototype = {
    _init:function(){
        if(this.type=="sp"){  // sp sector.
            this.data = SP_Sector;
        }else{                 // morningstar sector.
            this.data = MS_Sector;
        }
        this._buildPage();

		this.scrollPanel.reSize(this.cfg.width,this.cfg.height);
    },
	hide:function(){
		this.$container.hide();
		this.scrollPanel.el.hide();
	},
	show:function(){
		this.$container.show();
		this.scrollPanel.el.show();
		if(this.bChangeOutSized){
			this.scrollPanel.reSize(this.cfg.width,this.cfg.height);
			this.bChangeOutSized=false;
		}
	},
	changeOutSize:function(w,h){
		this.$container.css({width:w,height:h});
		this.scrollPanel.reSize(w,h);
		this.cfg.width=w;
		this.cfg.height=h;
		this.bChangeOutSized=true;
	},
    _buildPage:function(){
		var classPrefix="qs-sector-";
		var ellipsisClassName="qs-text-ellipsis";
        var str = [];
        var counts = Math.ceil(this.data.length/this.cols);
        for(var i=0;i<this.cols;i++){
            str[i]='<ul>';
        }
        var inx = 0,data = this.data;
        for(var i=0;i<data.length;i++){
            if(counts*(inx+1)<=i) inx++;
            str[inx]+='<li class="qs-sector-level1 '+classPrefix + data[i].name.toLowerCase().replace(/\s/g,"_")+" "+ellipsisClassName+'">';
            str[inx]+='<a class="qs-sector-level1-a qs-sector-til '+ellipsisClassName+'"><em>'+data[i].name+'</em><span class="qs-sector-btn"></span>'+'</a>';str[inx]+='';
            if(data[i].items&&data[i].items.length){
                str[inx]+='<ul>';
                for(var j=0;j<data[i].items.length;j++){
                    str[inx]+='<li class="qs-sector-level2"><a class="qs-sector-level2-a '+ellipsisClassName+'">'+data[i].items[j].name+'</a>';str[inx]+='';
                    if(data[i].items[j].items&&data[i].items[j].items.length){
                        str[inx]+='<ul>';
                        var dd;
                        for(var h=0;h<data[i].items[j].items.length;h++){
                            dd = data[i].items[j].items[h];
                            str[inx]+='<li class="qs-sector-level3">'
                            str[inx]+='<a class="qs-sector-level3-a '+ellipsisClassName+'" value="'+dd.id+'" href="javascript:void(0)">'+dd.name+'</a>';
                            str[inx]+='</li>';
                        }
                        str[inx]+='</ul>';
                    }
                    str[inx]+='</li>';
                }
                str[inx]+='</ul>'
            }
            str[inx]+='</li>';
        }
        for(var i=0;i<this.cols;i++){
            str[i]+='</ul>';
        }
        var strr = '<div class="qs-gd tri">'
         for (var i = 0; i < this.cols; i++) {
             var cls = i==0?" first":"";
             strr+='<div class="qs-c '+cls+'">'+str[i]+'</div>';
         }
         strr+="</div>"
         this.$container.html(strr);
         var self = this;
		 this.$container.find(".qs-sector-btn").unbind("click").bind("click",function(e){
			var t = $(e.target);
			t.parent().nextAll().last().slideToggle();
			t.toggleClass("qs-sector-btn-close");
		 });
         this.$container.find(".qs-sector-level3 a").unbind("click").bind("click",function(e){
             var t = $(e.target);
             var code = t.attr("value"),name = t.text();
             var url = "";
			 if(typeof(self.callback.onClick)=="function"){
				self.callback.onClick(code,self.type,self.region, name);
			 }
			 /*
             if(self.type=="ms"){
                 url = self.linkBaseUrl+"&sector="+code+"&ty=sector&view=sector&sy=ms&region="+self.region;
             }else{
                 url = self.linkBaseUrl+"&sector="+code+"&ty=sector&view=sector&sy=sp&region="+self.region;
             }
             var ls = url.split("?");
             url = ls[0]+ "?"+encodeURI(ls[1]);
             window.open(url,code,'width=800,height=500,top=100,left=30,location=no,toolbar=no,menubar=no');
			 */
         });
    }
}
